package org.jeecg.modules.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.entity.IdBaseEntity;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.api.enums.TradeStatusEnum;
import org.jeecg.modules.api.vo.*;
import org.jeecg.modules.api.vo.param.PaymentConfirmationParamVo;
import org.jeecg.modules.api.vo.param.PaymentParamVo;
import org.jeecg.modules.api.vo.param.QueryOrdersParamVo;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.zcgl.entity.*;
import org.jeecg.modules.zcgl.enums.*;
import org.jeecg.modules.zcgl.service.*;
import org.jeecg.modules.zcgl.util.NoUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;


@Api(tags = "三峡银行接口-缴费信息DEMO")
@RestController
@RequestMapping("/apiDemo/bank/order")
@Slf4j
public class OrdersApiControllerBack {

    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderDetailsService orderDetailsService;


    @Autowired
    private IOrderPrestoreService orderPrestoreService;
    @Autowired
    private IReceivablesInfoService receivablesInfoService;
    @Autowired
    private ICustomerInfoService customerInfoService;
    @Autowired
    private ISysDepartService sysDepartService;
    @Autowired
    private ISysDictService dictService;

    @Value("${weChat.notify_url}")
    private String notify_url;

    @ApiOperation(value = "待缴费信息-分页列表查询", notes = "待缴费信息-分页列表查询")
    @PostMapping(value = "/queryOrderList")
    public Result<IPage<ReceivablesRestBaVo>> queryOrderList(@RequestBody @Validated QueryOrdersParamVo paramVo,
                                                             HttpServletRequest req) {

//        if (paramVo.getCustomersIds().length == 0) {
//            return Result.errorValidation("客户ID不能为空");
//        }
        QueryWrapper<ReceivablesInfo> queryWrapper = new QueryWrapper<>();
        ReceivablesInfo receivablesInfo = new ReceivablesInfo();
        if (StringUtils.isNotBlank(paramVo.getRecordedCompanyName())){
            String companyId = sysDepartService.selectCompanyIdByName(paramVo.getRecordedCompanyName());
            if (StringUtils.isBlank(companyId)){
                return Result.errorValidation("公司名称信息错误！");
            }
            receivablesInfo.setRentCompanyId(companyId);
        }
        receivablesInfo.setPayStatus(PayStatusEnum.UNPAID.getStatus());
        receivablesInfo.setAmountConfirmation(YesNoEnum.YES.getStatus());
        queryWrapper.setEntity(receivablesInfo);
        final String customerSql = QueryGenerator.getCustomerSql(Arrays.asList(paramVo.getCustomerId()));
        queryWrapper.and(i -> i.apply(customerSql));
        queryWrapper.apply("DATE(pay_start_date) <= DATE('"+ DateUtils.now()+"')");
        queryWrapper.lambda().orderByAsc(IdBaseEntity::getId);

//        IPage<ReceivablesInfo> receivablesInfoIPage = receivablesInfoService.page(new Page<>(paramVo.getPageNo(), paramVo.getPageSize()), queryWrapper);
//        Map<String, ReceivablesRestBaVo> restBaVoMap = new HashMap<>();
//        receivablesInfoIPage.getRecords().stream().forEach(info -> {
//            ReceivablesRestVo restVo = new ReceivablesRestVo();
//            BeanUtils.copyProperties(info, restVo, "paymentInstructions");
//            restVo.setEndDate(info.getEndTime());
//            restVo.setStartDate(info.getStartTime());
//            restVo.setAmountMoney(info.getUnAmountMoney());
//            restVo.setPaymentInstructions(dictService.queryDictTextByKey("payment_instructions", String.valueOf(info.getPaymentInstructions())));
//
//            String key = info.getLeaseContractId() + info.getAssetId() + info.getAssetSubIds();
//            ReceivablesRestBaVo vo = restBaVoMap.get(key);
//            if (vo != null){
//                vo.setAmountMoney(vo.getAmountMoney().add(restVo.getAmountMoney()));
//                vo.getReceivablesList().add(restVo);
//            } else {
//                vo = new ReceivablesRestBaVo();
//                vo.setAmountMoney(info.getUnAmountMoney());
//                vo.setRecordedCompanyName(sysDepartService.getNameById(info.getCustomerId()));
//                vo.setContractNum(dictService.queryTableDictTextByKey("zcgl_lease_contract_info", "contract_num", "id", info.getLeaseContractId()));
//                if (StringUtils.isNotBlank(info.getAssetId())) {
//                    vo.setAssetSite(StringUtils.join(dictService.queryTableDictByKeys("zcgl_asset_info", "site", "id", info.getAssetId().split(CommonConstant.DEFAULT_SEPARATOR)), CommonConstant.DEFAULT_SEPARATOR));
//                }
//                if (StringUtils.isNotBlank(info.getCustomerId())) {
//                    vo.setCustomerName(StringUtils.join(dictService.queryTableDictByKeys("zcgl_customer_info", "name", "id", info.getCustomerId().split(CommonConstant.DEFAULT_SEPARATOR)), CommonConstant.DEFAULT_SEPARATOR));
//                }
//                if (StringUtils.isNotBlank(info.getAssetSubIds())) {
//                    vo.setAssetDetailsRoomName(StringUtils.join(dictService.queryTableDictByKeys("zcgl_asset_info_sub", "room_name", "id", info.getAssetSubIds().split(CommonConstant.DEFAULT_SEPARATOR)), CommonConstant.DEFAULT_SEPARATOR));
//                }
//                List<ReceivablesRestVo> receivablesList = new ArrayList<>();
//                receivablesList.add(restVo);
//                vo.setReceivablesList(receivablesList);
//                restBaVoMap.put(key, vo);
//            }
//        });
//
//        List<ReceivablesRestBaVo> voList = new ArrayList<>();
//        Page<ReceivablesRestBaVo> pageList = new Page<>();
//        BeanUtils.copyProperties(receivablesInfoIPage, pageList, "records");
//        for(ReceivablesRestBaVo m : restBaVoMap.values()){
//            voList.add(m);
//        }
//        pageList.setRecords(voList);
//        return Result.ok(pageList);

        queryWrapper.select("SUM(un_amount_money) AS amount_money,lease_contract_id, customer_id, asset_sub_ids, asset_id, rent_company_id");
        queryWrapper.lambda().groupBy(ReceivablesInfo::getLeaseContractId, ReceivablesInfo::getAssetId, ReceivablesInfo::getAssetSubIds);

        IPage<ReceivablesInfo> receivablesInfoIPage = receivablesInfoService.page(new Page<>(paramVo.getPageNo(), paramVo.getPageSize()), queryWrapper);
        List<ReceivablesRestBaVo> voList = new ArrayList<>();
        receivablesInfoIPage.getRecords().stream().forEach(info -> {
            ReceivablesRestBaVo vo = new ReceivablesRestBaVo();
            vo.setAmountMoney(info.getAmountMoney());
            vo.setRecordedCompanyName(sysDepartService.getNameById(info.getRentCompanyId()));
            vo.setContractNum(dictService.queryTableDictTextByKey("zcgl_lease_contract_info", "contract_num", "id", info.getLeaseContractId()));
            if (StringUtils.isNotBlank(info.getAssetId())) {
                vo.setAssetSite(StringUtils.join(dictService.queryTableDictByKeys("zcgl_asset_info", "site", "id", info.getAssetId().split(CommonConstant.DEFAULT_SEPARATOR)), CommonConstant.DEFAULT_SEPARATOR));
            }
            if (StringUtils.isNotBlank(info.getCustomerId())) {
                vo.setCustomerName(StringUtils.join(dictService.queryTableDictByKeys("zcgl_customer_info", "name", "id", info.getCustomerId().split(CommonConstant.DEFAULT_SEPARATOR)), CommonConstant.DEFAULT_SEPARATOR));
            }
            if (StringUtils.isNotBlank(info.getAssetSubIds())) {
                vo.setAssetDetailsRoomName(StringUtils.join(dictService.queryTableDictByKeys("zcgl_asset_info_sub", "room_name", "id", info.getAssetSubIds().split(CommonConstant.DEFAULT_SEPARATOR)), CommonConstant.DEFAULT_SEPARATOR));
            }


            LambdaQueryWrapper<ReceivablesInfo> voQueryWrapper = new LambdaQueryWrapper<>();
            voQueryWrapper.setEntity(receivablesInfo);

            if ( info.getCustomerId() != null){
                voQueryWrapper.eq(ReceivablesInfo::getCustomerId, info.getCustomerId());
            } else {
                voQueryWrapper.isNull(ReceivablesInfo::getCustomerId);
            }
            if ( info.getAssetId() != null){
                voQueryWrapper.eq(ReceivablesInfo::getAssetId, info.getAssetId());
            } else {
                voQueryWrapper.and(i ->{
                    i.isNull(ReceivablesInfo::getAssetId).or().eq(ReceivablesInfo::getAssetId, "''");
                });
            }
            if ( info.getAssetSubIds() != null){
                voQueryWrapper.eq(ReceivablesInfo::getAssetSubIds, info.getAssetSubIds());
            } else {
                voQueryWrapper.isNull(ReceivablesInfo::getAssetSubIds);
            }

            voQueryWrapper.apply("DATE(pay_start_date) <= DATE('"+ DateUtils.now()+"')");
            voQueryWrapper.orderByAsc(IdBaseEntity::getId);

            List<ReceivablesInfo> detailList = receivablesInfoService.list(voQueryWrapper);
            List<ReceivablesRestVo> receivablesList = new ArrayList<>();
            if (detailList != null){
                detailList.forEach(detail->{
                    ReceivablesRestVo restVo = new ReceivablesRestVo();
                    BeanUtils.copyProperties(detail, restVo, "paymentInstructions");
                    restVo.setEndDate(DateUtils.formatDate(detail.getEndTime()));
                    restVo.setStartDate(DateUtils.formatDate(detail.getStartTime()));
                    restVo.setAmountMoney(detail.getUnAmountMoney());
                    restVo.setPaymentInstructions(dictService.queryDictTextByKey("payment_instructions", String.valueOf(detail.getPaymentInstructions())));
                    receivablesList.add(restVo);
                });
            }
            vo.setReceivablesList(receivablesList);
            voList.add(vo);
        });
        Page<ReceivablesRestBaVo> pageList = new Page<>();
        BeanUtils.copyProperties(receivablesInfoIPage, pageList, "records");
        pageList.setRecords(voList);
        return Result.ok(pageList);
    }

    @ApiOperation(value = "待缴费信息-缴费确认", notes = "待缴费信息-缴费确认")
    @PostMapping(value = "/paymentConfirmation")
    public Result paymentConfirmation(@RequestBody @Validated PaymentConfirmationParamVo vo,
                                      HttpServletRequest request, HttpServletResponse response) {
        if (vo.getOrderIds().size() == 0){
            return Result.errorValidation("待付款信息ID不能为空");
        }
//        if (vo.getPayeeList().size() == 0){
//            return Result.errorValidation("收款方信息不能为空");
//        }
        List<ReceivablesInfo> receivablesInfoList = new ArrayList<>();
        BigDecimal totalAmount = BigDecimal.ZERO;

        //查询支付订单号是否已存在，如果存在表示已处理过，直接返回
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        Order order = new Order();
        order.setTransactionId(vo.getTransactionId());
        queryWrapper.setEntity(order);
        Integer num = orderService.count(queryWrapper);
        if (num != null && num > 0) {
            return Result.ok("支付处理成功！");
        }


        String companyId = sysDepartService.selectCompanyIdByName(vo.getRecordedCompanyName());
        if (StringUtils.isBlank(companyId)) {
            throw new JeecgBootException("入账公司不存在，支付处理失败！");
        }
        vo.setRecordedCompanyId(companyId);

        Map<String, BigDecimal> companyTotalAmountMap = new HashMap<>();
        for (String id : vo.getOrderIds()) {
            ReceivablesInfo receivablesInfo = receivablesInfoService.getById(id);
            if (receivablesInfo == null || (receivablesInfo.getPayStatus() != null && PayStatusEnum.UNPAID.getStatus() != receivablesInfo.getPayStatus().intValue())){
                throw new JeecgBootException("有付款信息不存在或已支付，支付处理失败！");
            }
            if (!receivablesInfo.getRentCompanyId().equalsIgnoreCase(companyId)){
                throw new JeecgBootException("有入账单位不一致，支付处理失败！");
            }
//            if (receivablesInfo.getPayStatus() != null && PayStatusEnum.UNPAID.getStatus() != receivablesInfo.getPayStatus().intValue()){
//                throw new JeecgBootException("有付款信息不存在或已支付，支付失败！");
//            }
            totalAmount = totalAmount.add(receivablesInfo.getUnAmountMoney());
            receivablesInfoList.add(receivablesInfo);
            BigDecimal companyTotalAmount = companyTotalAmountMap.get(receivablesInfo.getRentCompanyId());
            if (companyTotalAmount ==null){
                companyTotalAmount = receivablesInfo.getUnAmountMoney();
            } else {
                companyTotalAmount = companyTotalAmount.add(receivablesInfo.getUnAmountMoney());
            }
            companyTotalAmountMap.put(receivablesInfo.getRentCompanyId(), companyTotalAmount);
        }

        if (totalAmount.compareTo(new BigDecimal(vo.getAmountMoney()/100.0).setScale(2, BigDecimal.ROUND_HALF_UP)) != 0){
            return Result.error("款项总金额不一致，支付处理失败！");
        }

//        vo.getPayeeList().stream().forEach(payee -> {
//            String id = sysDepartService.selectCompanyIdByName(payee.getRecordedCompanyName());
//            if (StringUtils.isBlank(id)){
//                throw new JeecgBootException("有入账公司不存在，支付失败！");
//            }
//            BigDecimal a = new BigDecimal(payee.getMoney()/100.0).setScale(2, BigDecimal.ROUND_HALF_UP);
//            if (companyTotalAmountMap.get(id) == null || companyTotalAmountMap.get(id).compareTo(a) != 0){
//                throw new JeecgBootException("有公司入账金额不一致，支付失败！");
//            }
//            payee.setRecordedCompanyId(id);
//        });

        boolean bool = receivablesInfoService.paymentConfirmation(vo, receivablesInfoList);

        if (bool){
            return Result.ok("支付处理成功！");
        } else {
            return Result.error("支付处理失败！");
        }

    }

    @ApiOperation(value = "缴费信息-预存缴费", notes = "缴费信息-预存缴费")
    @PostMapping(value = "/paymentPrestore")
    public Result paymentPrestore(@RequestBody @Validated PaymentParamVo vo,
                                  HttpServletRequest request, HttpServletResponse response) {
        CustomerInfo customerInfo = customerInfoService.getById(vo.getCustomerId());
        if (customerInfo == null){
            return Result.error("客户信息错误！");
        }
        SysDepart company = sysDepartService.selectCompanyByName(vo.getRecordedCompanyName());
//            String companyId = sysDepartService.selectCompanyIdByName(vo.getRecordedCompanyName());
        if (company == null) {
            return Result.error("入账公司信息错误！");
        }
        //查询预存订单号是否已存在，如果存在表示已处理过，直接返回
        QueryWrapper<OrderPrestore> queryWrapper = new QueryWrapper<>();
        OrderPrestore order = new OrderPrestore();
        order.setTransactionId(vo.getTransactionId());
        queryWrapper.setEntity(order);
        Integer num = orderPrestoreService.count(queryWrapper);
        if (num != null && num > 0) {
            return Result.ok("预存成功！");
        }


        //生成预存订单
        boolean tradeStatus = TradeStatusEnum.SUCCESS.getKey().equalsIgnoreCase(vo.getTradeStatus());
        OrderPrestore orderPrestore = new OrderPrestore();
        BeanUtils.copyProperties(vo, orderPrestore, "amountMoney", "tradeTime");
        orderPrestore.setCompanyId(company.getId());
        orderPrestore.setSysOrgCode(company.getSysOrgCode());
        orderPrestore.setRentCompanyId(company.getId());
        orderPrestore.setAmountMoney(new BigDecimal(vo.getAmountMoney() / 100.0).setScale(2, BigDecimal.ROUND_HALF_UP));
        orderPrestore.setPayType(PayTypeEnum.CCQTGB.getStatus());
        orderPrestore.setPayStatus(tradeStatus ? AttentionPayStatusEnum.SUCCESSFUL.getStatus() : AttentionPayStatusEnum.FAILED.getStatus());
        orderPrestore.setOrderNo(NoUtils.getOrderNo());
        orderPrestore.setTradeTime(DateUtils.parseDate(vo.getTradeTime()));
        //预存处理
        //orderPrestoreService.saveAndCustomerBalance(orderPrestore);

        return Result.ok("预存成功！");
    }

    @ApiOperation(value = "缴费信息-查询预存缴费记录", notes = "缴费信息-查询预存缴费记录")
    @PostMapping(value = "/queryPaymentPrestore")
    public Result<IPage<PaymentPrestoreVo>> queryPaymentPrestore(@RequestBody @Validated QueryOrdersParamVo vo,
                                                                 HttpServletRequest request, HttpServletResponse response) {

//        if (vo.getCustomersIds().length == 0) {
//            return Result.errorValidation("客户ID不能为空");
//        }
        QueryWrapper<OrderPrestore> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(vo.getRecordedCompanyName())){
            String companyId = sysDepartService.selectCompanyIdByName(vo.getRecordedCompanyName());
            if (StringUtils.isBlank(companyId)){
                return Result.errorValidation("公司名称信息错误！");
            }
            queryWrapper.lambda().eq(OrderPrestore::getRentCompanyId, companyId);
        }
        queryWrapper.lambda().in(OrderPrestore::getCustomerId, vo.getCustomerId());
        queryWrapper.lambda().orderByDesc(IdBaseEntity::getId);
        IPage<OrderPrestore> orderPrestoreIPage = orderPrestoreService.page(new Page<>(vo.getPageNo(), vo.getPageSize()), queryWrapper);
        List<PaymentPrestoreVo> voList = new ArrayList<>();
        orderPrestoreIPage.getRecords().forEach(prestore->{
            PaymentPrestoreVo restVo = new PaymentPrestoreVo();
            BeanUtils.copyProperties(prestore, restVo);
            restVo.setTradeTime(DateUtils.formatDateTime(prestore.getTradeTime()));
            restVo.setRecordedCompanyName(sysDepartService.getNameById(prestore.getRentCompanyId()));
            voList.add(restVo);
        });

        Page<PaymentPrestoreVo> pageList = new Page<>();
        BeanUtils.copyProperties(orderPrestoreIPage, pageList, "records");
        pageList.setRecords(voList);
        return Result.ok(pageList);
    }

    @ApiOperation(value = "缴费信息-查询自动扣费记录", notes = "缴费信息-查询自动扣费记录")
    @PostMapping(value = "/queryAutomaticDeduction")
    public Result<IPage<OrderDetailsBVo>> queryAutomaticDeduction(@RequestBody @Validated QueryOrdersParamVo vo,
                                                                  HttpServletRequest request, HttpServletResponse response) {

//        if (vo.getCustomersIds().length == 0) {
//            return Result.errorValidation("客户ID不能为空");
//        }
        QueryWrapper<OrderDetails> queryWrapper = new QueryWrapper<>();
        OrderDetails orderDetails = new OrderDetails();
        if (StringUtils.isNotBlank(vo.getRecordedCompanyName())){
            String companyId = sysDepartService.selectCompanyIdByName(vo.getRecordedCompanyName());
            if (StringUtils.isBlank(companyId)){
                return Result.errorValidation("公司名称信息错误！");
            }
            orderDetails.setRentCompanyId(companyId);
        }
        orderDetails.setPayStatus(AttentionPayStatusEnum.SUCCESSFUL.getStatus());
        orderDetails.setPayType(PayTypeEnum.AUTOMATIC_DEDUCTION.getStatus());
        orderDetails.setOrderType(OrderTypeEnum.AUTOMATIC_DEDUCTION.getStatus());
        queryWrapper.setEntity(orderDetails);
        queryWrapper.lambda().orderByDesc(OrderDetails::getPayDate);
        queryWrapper.lambda().in(OrderDetails::getPaymentBy, vo.getCustomerId());
        queryWrapper.lambda().orderByDesc(IdBaseEntity::getId);
        IPage<OrderDetails> receivablesInfoIPage = orderDetailsService.page(new Page<>(vo.getPageNo(), vo.getPageSize()), queryWrapper);

        List<OrderDetailsBVo> voList = new ArrayList<>();
        receivablesInfoIPage.getRecords().forEach(info->{
            OrderDetailsBVo restVo = new OrderDetailsBVo();
            BeanUtils.copyProperties(info, restVo);
            restVo.setRecordedCompanyName(sysDepartService.getNameById(info.getRentCompanyId()));
            restVo.setContractNum(dictService.queryTableDictTextByKey("zcgl_lease_contract_info", "contract_num", "id", info.getLeaseContractId()));
            if (StringUtils.isNotBlank(info.getAssetId())) {
                restVo.setAssetSite(StringUtils.join(dictService.queryTableDictByKeys("zcgl_asset_info", "site", "id", info.getAssetId().split(CommonConstant.DEFAULT_SEPARATOR)), CommonConstant.DEFAULT_SEPARATOR));
            }
            if (StringUtils.isNotBlank(info.getCustomerId())) {
                restVo.setCustomerName(StringUtils.join(dictService.queryTableDictByKeys("zcgl_customer_info", "name", "id", info.getCustomerId().split(CommonConstant.DEFAULT_SEPARATOR)), CommonConstant.DEFAULT_SEPARATOR));
            }
            if (StringUtils.isNotBlank(info.getAssetSubIds())) {
                restVo.setAssetDetailsRoomName(StringUtils.join(dictService.queryTableDictByKeys("zcgl_asset_info_sub", "room_name", "id", info.getAssetSubIds().split(CommonConstant.DEFAULT_SEPARATOR)), CommonConstant.DEFAULT_SEPARATOR));
            }
            restVo.setEndDate(DateUtils.formatDate(info.getEndTime()));
            restVo.setStartDate(DateUtils.formatDate(info.getStartTime()));
            restVo.setAutomaticDeductionDate(DateUtils.formatDateTime(info.getPayDate()));
            restVo.setPaymentInstructions(dictService.queryDictTextByKey("payment_instructions", String.valueOf(info.getPaymentInstructions())));
            voList.add(restVo);
        });

        Page<OrderDetailsBVo> pageList = new Page<>();
        BeanUtils.copyProperties(receivablesInfoIPage, pageList, "records");
        pageList.setRecords(voList);
        return Result.ok(pageList);

//        QueryWrapper<ReceivablesInfo> queryWrapper = new QueryWrapper<>();
//        ReceivablesInfo receivablesInfo = new ReceivablesInfo();
//        receivablesInfo.setPayStatus(PayStatusEnum.PAID.getStatus());
//        receivablesInfo.setPayType(PayTypeEnum.AUTOMATIC_DEDUCTION.getStatus());
//        queryWrapper.setEntity(receivablesInfo);
//        queryWrapper.lambda().orderByDesc(ReceivablesInfo::getReceiptDate);
//        queryWrapper.lambda().in(ReceivablesInfo::getPaymentBy, vo.getCustomersIds());
//        IPage<ReceivablesInfo> receivablesInfoIPage = receivablesInfoService.page(new Page<>(vo.getPageNo(), vo.getPageSize()), queryWrapper);
//
//        List<OrderDetailsBVo> voList = new ArrayList<>();
//        receivablesInfoIPage.getRecords().forEach(info->{
//            OrderDetailsBVo restVo = new OrderDetailsBVo();
//            BeanUtils.copyProperties(info, restVo);
//            restVo.setRecordedCompanyName(sysDepartService.getNameById(info.getCompanyId()));
//            restVo.setContractNum(dictService.queryTableDictTextByKey("zcgl_lease_contract_info", "contract_num", "id", info.getLeaseContractId()));
//            if (StringUtils.isNotBlank(info.getAssetId())) {
//                restVo.setAssetSite(StringUtils.join(dictService.queryTableDictByKeys("zcgl_asset_info", "site", "id", info.getAssetId().split(CommonConstant.DEFAULT_SEPARATOR)), CommonConstant.DEFAULT_SEPARATOR));
//            }
//            if (StringUtils.isNotBlank(info.getCustomerId())) {
//                restVo.setCustomerName(StringUtils.join(dictService.queryTableDictByKeys("zcgl_customer_info", "name", "id", info.getCustomerId().split(CommonConstant.DEFAULT_SEPARATOR)), CommonConstant.DEFAULT_SEPARATOR));
//            }
//            if (StringUtils.isNotBlank(info.getAssetSubIds())) {
//                restVo.setAssetDetailsRoomName(StringUtils.join(dictService.queryTableDictByKeys("zcgl_asset_info_sub", "room_name", "id", info.getAssetSubIds().split(CommonConstant.DEFAULT_SEPARATOR)), CommonConstant.DEFAULT_SEPARATOR));
//            }
//            restVo.setEndDate(info.getEndTime());
//            restVo.setStartDate(info.getStartTime());
//            restVo.setAutomaticDeductionDate(info.getReceiptDate());
//            restVo.setPaymentInstructions(dictService.queryDictTextByKey("payment_instructions", String.valueOf(info.getPaymentInstructions())));
//            voList.add(restVo);
//        });
//
//        Page<OrderDetailsBVo> pageList = new Page<>();
//        BeanUtils.copyProperties(receivablesInfoIPage, pageList, "records");
//        pageList.setRecords(voList);
//        return Result.ok(pageList);
    }

    @ApiOperation(value = "缴费信息-缴费记录查询", notes = "缴费信息-缴费记录查询")
    @PostMapping(value = "/queryPaymentList")
    public Result<IPage<OrderDetailsRestVo>> queryPaymentList(@RequestBody @Validated QueryOrdersParamVo paramVo,
                                                              HttpServletRequest req) {

//        if (paramVo.getCustomersIds().length == 0) {
//            return Result.errorValidation("客户ID不能为空");
//        }
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
//        final String customerSql = QueryGenerator.getCustomerSql(Arrays.asList(paramVo.getCustomersId()));
//        queryWrapper.and(i -> i.apply(customerSql));
        if (StringUtils.isNotBlank(paramVo.getRecordedCompanyName())){
            String companyId = sysDepartService.selectCompanyIdByName(paramVo.getRecordedCompanyName());
            if (StringUtils.isBlank(companyId)){
                return Result.errorValidation("公司名称信息错误！");
            }
            queryWrapper.lambda().eq(Order::getRentCompanyId, companyId);
        }
        queryWrapper.lambda().eq(Order::getCustomerId, paramVo.getCustomerId());
        queryWrapper.lambda().orderByDesc(IdBaseEntity::getId);
        IPage<Order> orderIPage = orderService.page(new Page<>(paramVo.getPageNo(), paramVo.getPageSize()), queryWrapper);
        List<OrderDetailsRestVo> voList = new ArrayList<>();
        orderIPage.getRecords().stream().forEach(info -> {
            OrderDetailsRestVo vo = new OrderDetailsRestVo();
            BeanUtils.copyProperties(info, vo);
            vo.setTradeTime(DateUtils.formatDateTime(info.getTradeTime()));
            vo.setOrderType(dictService.queryDictTextByKey("zcgl_order_type", String.valueOf(info.getOrderType())));

            List<OrderDetailsRestDetailVo> orderDetailsRestDetailVos = new ArrayList<>();
            List<OrderDetails> orderDetails = orderDetailsService.selectByMainId(info.getId());
            if (orderDetails != null){
                orderDetails.stream().forEach(details -> {
                    OrderDetailsRestDetailVo detailVo = new OrderDetailsRestDetailVo();
                    BeanUtils.copyProperties(details, detailVo);
                    detailVo.setRecordedCompanyName(sysDepartService.getNameById(details.getRentCompanyId()));
                    detailVo.setContractNum(dictService.queryTableDictTextByKey("zcgl_lease_contract_info", "contract_num", "id", details.getLeaseContractId()));
                    if (StringUtils.isNotBlank(details.getAssetId())) {
                        detailVo.setAssetSite(StringUtils.join(dictService.queryTableDictByKeys("zcgl_asset_info", "site", "id", details.getAssetId().split(CommonConstant.DEFAULT_SEPARATOR)), CommonConstant.DEFAULT_SEPARATOR));
                    }
                    if (StringUtils.isNotBlank(details.getCustomerId())) {
                        detailVo.setCustomerName(StringUtils.join(dictService.queryTableDictByKeys("zcgl_customer_info", "name", "id", details.getCustomerId().split(CommonConstant.DEFAULT_SEPARATOR)), CommonConstant.DEFAULT_SEPARATOR));
                    }
                    if (StringUtils.isNotBlank(details.getAssetSubIds())) {
                        detailVo.setAssetDetailsRoomName(StringUtils.join(dictService.queryTableDictByKeys("zcgl_asset_info_sub", "room_name", "id", details.getAssetSubIds().split(CommonConstant.DEFAULT_SEPARATOR)), CommonConstant.DEFAULT_SEPARATOR));
                    }
                    detailVo.setPaymentInstructions(dictService.queryDictTextByKey("payment_instructions", String.valueOf(details.getPaymentInstructions())));
                    detailVo.setEndDate(DateUtils.formatDate(details.getEndTime()));
                    detailVo.setStartDate(DateUtils.formatDate(details.getStartTime()));
                    orderDetailsRestDetailVos.add(detailVo);
                });
            }
            vo.setOrderDetails(orderDetailsRestDetailVos);

            voList.add(vo);
        });
        Page<OrderDetailsRestVo> pageList = new Page<>();
        BeanUtils.copyProperties(orderIPage, pageList, "records");
        pageList.setRecords(voList);

        return Result.ok(pageList);
    }
}
